import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as authApi from '@/api/auth'
import * as userApi from '@/api/user'
import type { UserInfo, LoginData, RegisterData } from '@/api/auth'
import type { UserStats } from '@/api/user'
import { getDeviceInfo } from '@/utils/common'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const userStats = ref<UserStats | null>(null)
  const token = ref<string>('')
  const isLoading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const userId = computed(() => userInfo.value?.id)
  const nickname = computed(() => userInfo.value?.nickname || '用户')
  const avatar = computed(() => userInfo.value?.avatar)

  /**
   * 用户登录
   */
  const login = async (data: LoginData) => {
    try {
      isLoading.value = true

      // 添加设备信息
      const deviceInfo = getDeviceInfo()
      const loginData = {
        ...data,
        device_info: deviceInfo
      }

      const response = await authApi.login(loginData)

      // 保存用户信息和token
      userInfo.value = response.user
      token.value = response.token

      // 持久化存储
      uni.setStorageSync('token', response.token)
      uni.setStorageSync('user_info', response.user)

      return response

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 用户注册
   */
  const register = async (data: RegisterData) => {
    try {
      isLoading.value = true
      return await authApi.register(data)
    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 微信登录
   */
  const wechatLogin = async (code: string, userInfo?: any) => {
    try {
      isLoading.value = true

      const deviceInfo = getDeviceInfo()
      const response = await authApi.wechatLogin({
        code,
        platform: 'mini',
        device_info: deviceInfo
      })

      // 保存登录信息
      userInfo.value = response.user
      token.value = response.token

      uni.setStorageSync('token', response.token)
      uni.setStorageSync('user_info', response.user)

      return response

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 支付宝登录
   */
  const alipayLogin = async (authCode: string) => {
    try {
      isLoading.value = true

      const deviceInfo = getDeviceInfo()
      const response = await authApi.alipayLogin({
        code: authCode,
        device_info: deviceInfo
      })

      userInfo.value = response.user
      token.value = response.token

      uni.setStorageSync('token', response.token)
      uni.setStorageSync('user_info', response.user)

      return response

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 抖音登录
   */
  const douyinLogin = async (code: string) => {
    try {
      isLoading.value = true

      const deviceInfo = getDeviceInfo()
      const response = await authApi.douyinLogin({
        code,
        device_info: deviceInfo
      })

      userInfo.value = response.user
      token.value = response.token

      uni.setStorageSync('token', response.token)
      uni.setStorageSync('user_info', response.user)

      return response

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 刷新Token
   */
  const refreshToken = async () => {
    try {
      const currentToken = token.value || uni.getStorageSync('token')
      if (!currentToken) {
        throw new Error('Token不存在')
      }

      const response = await authApi.refreshToken(currentToken)
      token.value = response.token

      uni.setStorageSync('token', response.token)

      return response

    } catch (error) {
      // Token刷新失败，清除登录状态
      logout()
      throw error
    }
  }

  /**
   * 退出登录
   */
  const logout = async (callApi = true) => {
    try {
      if (callApi && token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('退出登录API调用失败:', error)
    } finally {
      // 清除状态
      userInfo.value = null
      userStats.value = null
      token.value = ''

      // 清除存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('user_info')
      uni.removeStorageSync('master_password')
      uni.removeStorageSync('encrypt_config')
    }
  }

  /**
   * 加载用户数据
   */
  const loadUserData = async () => {
    try {
      isLoading.value = true

      const response = await userApi.getUserInfo()
      userInfo.value = response.user
      userStats.value = response.stats

      // 更新存储
      uni.setStorageSync('user_info', response.user)

      return response

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新用户信息
   */
  const updateUserInfo = async (data: userApi.UpdateUserInfoData) => {
    try {
      isLoading.value = true

      const updatedUser = await userApi.updateUserInfo(data)
      userInfo.value = updatedUser

      uni.setStorageSync('user_info', updatedUser)

      return updatedUser

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 修改密码
   */
  const changePassword = async (data: userApi.ChangePasswordData) => {
    try {
      isLoading.value = true
      return await userApi.changePassword(data)
    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 初始化用户状态（从存储中恢复）
   */
  const initUserState = () => {
    try {
      const storedToken = uni.getStorageSync('token')
      const storedUserInfo = uni.getStorageSync('user_info')

      if (storedToken && storedUserInfo) {
        token.value = storedToken
        userInfo.value = storedUserInfo
      }
    } catch (error) {
      console.error('初始化用户状态失败:', error)
    }
  }

  /**
   * 清除用户状态
   */
  const clearUserState = () => {
    userInfo.value = null
    userStats.value = null
    token.value = ''
  }

  return {
    // 状态
    userInfo,
    userStats,
    token,
    isLoading,

    // 计算属性
    isLoggedIn,
    userId,
    nickname,
    avatar,

    // 方法
    login,
    register,
    wechatLogin,
    alipayLogin,
    douyinLogin,
    refreshToken,
    logout,
    loadUserData,
    updateUserInfo,
    changePassword,
    initUserState,
    clearUserState
  }
})